package com.tuling.jucdemo.sync;

import lombok.extern.slf4j.Slf4j;

/**
 * @author :tangweiliang
 * @date : 2022/11/9 21:31
 * 未来的你会感谢现在努力的你
 *
 * synchronized代码块
 */

@Slf4j
public class SynDemo2 {
    private static int count = 0;
    private static Object lock = new Object();

    private static void increment(){
        synchronized (lock){
            count++;
        }
    }

    private static void delcrement(){
        synchronized (lock){
            count--;
        }
    }

    public static void main(String[] args) throws InterruptedException {
        Thread t1 = new Thread(()->{
            for (int i = 0; i < 5000; i++) {
                increment();
            }
        },"t1");

        Thread t2 = new Thread(()->{
            for (int i = 0; i < 5000; i++) {
                delcrement();
            }
        },"t2");

        t1.start();
        t2.start();
        t1.join();
        t2.join();

        //思考count的次数
        log.info("count={}", count);
    }
}
